//连接mongoose，数据库统一取名为ABS
var mongoose = require('mongoose');
mongoose.connect('mongodb://120.79.253.131:27017/ABS', { useNewUrlParser: true, useUnifiedTopology: true });

//检查是否联系成功
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
  console.log('数据库链接成功')
});


var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
//定义路由的位置
var shops = require('./routes/shops');//商品
var login = require('./routes/login');//登入
var cart = require('./routes/cart');//购物车
var info = require('./routes/info');//个人信息
var address = require('./routes/address');//个人信息

const cors = require('cors');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//允许跨域
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//设置对应的路由前缀并调用该路由
app.use('/', shops);//无前缀
app.use('/', login);//无前缀
app.use('/', cart);//
app.use('/', info);//
app.use('/', address);//



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
